/*
 * Creado por Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

//Roles
var iConst = new fn_const();
function fn_const()
{
	this.NEW = "NEW";
	this.EDIT = "EDIT";
	this.DELETE = "DELETE";
	this.DELETEITEM = "DELETEITEM";
	this.CONSULT = "CONSULT";
	this.UPLOAD = "UPLOAD";
	this.ADD = "ADD";
	this.UPDATE = "UPDATE";
	this.VIEW_CALC_PUNTOS = "VIEW_CALC_PUNTOS";
	this.EDIT_RESULT = "EDIT_RESULT";
}

var iConstTipoCarrera = new fn_constTipoCarrera();
function fn_constTipoCarrera()
{
	this.GENERAL = "G";
	this.FONDO = "F";
	this.EXTRA = "E";
	this.UNA_PTA = "P";
}

var classConst = new fn_classConst();
function fn_classConst()
{
	this.HIGHLIGHT = "ui-state-highlight";
	this.ERROR = "ui-state-error";
}

function $_ajax_showLoader(loaderId)
{
	$('#' + loaderId).show();
}

function $_ajax_hideLoader(loaderId)
{
	$('#' + loaderId).hide();
}

function $_trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

function $_replace(s, r, w){
     return s.split(r).join(w);
}

function $_zeroPad(num) { 

	var s = '0'+num;

	return s.substring(s.length-2) 
};

function $_getPageScrollTop(){
	var yScrolltop;
	var xScrollleft;
	if (self.pageYOffset || self.pageXOffset) {
		yScrolltop = self.pageYOffset;
		xScrollleft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){	 // Explorer 6 Strict
		yScrolltop = document.documentElement.scrollTop;
		xScrollleft = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScrolltop = document.body.scrollTop;
		xScrollleft = document.body.scrollLeft;
	}
	arrayPageScroll = new Array(xScrollleft,yScrolltop) 
	return arrayPageScroll;
}

function $_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}

/** GLOBAL MESSAGE **/
var isShown = false;
var request_timer = false;

setTimeout(function(){$("#globalMessImgClose").click($_closeMessage);}, 500);

function $_closeMessage()
{
	$('#globalMess').fadeOut();
	isShown = false;
}

function $_showMessage(tipo, titulo, mensaje, timeOut)
{
	var messageTimeOut = 5000; // 5 segundos

	if(timeOut !== undefined)
		messageTimeOut = timeOut;

	//configuramos la estetica del mensaje
	$('#globalMess').removeClass();
	switch(tipo)
	{
		case "ERR": // si es un mensaje de error
			$('#globalMess').addClass('mensajesErr');
			break;
		case "OK": // si es un mensaje de ok
			$('#globalMess').addClass('mensajesOk');
			break;
		case "ALERT": // si es un mensaje de alerta
			$('#globalMess').addClass('mensajesAlert');
			break;
	}

	$('#tituloMess').html(titulo);
	$('#textoMess').html(mensaje);
	
	$_centrar();
	if(!isShown){
		$('#globalMess').slideDown('fast');
		isShown = true;
	}
	
	// limpio timeout's pendientes, si es que hay!!
	if (request_timer)
		clearTimeout(request_timer);

	// utilizo un timer para ocultar el mensaje en un determinado tiempo (messageTimeOut)
	if(timeOut !== -1)
		request_timer = setTimeout($_closeMessage, messageTimeOut);
	
	//queremos que siempre se quede centrado horizontalmente y en la linea del scroll verticalmente
	$(window).scroll($_centrar);
	$(window).resize($_centrar);
}

function $_showUrgentMessage(tipo, titulo, mensaje, timeOut)
{
	//limpio el timeout pendiente, si es que hay!!
	if(request_timer)
		clearTimeout(request_timer);
	
	$('#globalMess').hide(); 
	isShown = false;

	$_showMessage(tipo, titulo, mensaje, timeOut);	
}

function $_centrar(){
	var pagesize = $_getPageSize();
	var arrayPageScroll = $_getPageScrollTop();
	$("#globalMess")
	.css(
		{
			left: (arrayPageScroll[0] + (pagesize[0] - $('#globalMess').width())/2) + "px",
			top:  arrayPageScroll[1] + "px"
		});
}
/** GLOBAL MESSAGE **/

function $_mailValido(mail)
{
	var filter  = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	if (filter.test(mail))
		return true;
	else 
		return false;
}

function $_highLightFormFields(arrFields)
{
	if(arrFields!=undefined){
		for (key in arrFields)
			$('#' + arrFields[key]).effect("highlight", {color:'#FF0000'}, 1000);
	}
}

/* Not implemented */
function $_notImplemented()
{
	$_showMessage('ALERT', 'ALERTA', 'Funci&oacute;n no implementada!');
}

function $_ValidatorSetDefaults()
{

	$.validator.setDefaults({
		invalidHandler:function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) 
			{			
				$_showMessage('ALERT', 'ALERTA', strMenssageErrorMandatoryFields);
				
				var invalidPanels = $(validator.invalidElements()).closest(".ui-tabs-panel", form);
				if (invalidPanels.size() > 0) 
				{
					 $.each($.unique(invalidPanels.get()), function() {
						 
				          $(this).siblings(".ui-tabs-nav")
				            .find("a[href='#" + this.id + "']").parent().not(".ui-tabs-selected")
				            .addClass(classConst.ERROR)
				            .show("pulsate",{times: 3});
				        });
				}
			}
		},
		highlight: function(input) {
		    $(input).addClass(classConst.HIGHLIGHT);
		},
		unhighlight: function(input) {
		    $(input).removeClass(classConst.HIGHLIGHT);
	
		    var $panel = $(input).closest(".ui-tabs-panel", input.form);
		    if ($panel.size() > 0) 
		    {
		    	if ($panel.find("." + classConst.HIGHLIGHT).size() == 0) 
			    {
			        $panel.siblings(".ui-tabs-nav").find("a[href='#" + $panel[0].id + "']")
			        .parent().removeClass(classConst.ERROR);
			    }
		    }
		}
	});
}

//Reload Datatables Server Side AJAX from original file 
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
	if ( typeof sNewSource != 'undefined' && sNewSource != null )    
	{
		oSettings.sAjaxSource = sNewSource;    
	}    
	this.oApi._fnProcessingDisplay( oSettings, true );    
	var that = this;    
	var iStart = oSettings._iDisplayStart;    
	var aData = [];     
	this.oApi._fnServerParams( oSettings, aData );         
	oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
		/* Clear the old information from the table */        
		that.oApi._fnClearTable( oSettings );                 
		/* Got the data - add it to the table */        
		var aData =  (oSettings.sAjaxDataProp !== "") ?            
			that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
			
		for ( var i=0 ; i<aData.length ; i++ )        
		{            
			that.oApi._fnAddData( oSettings, aData[i] );        
		}                 
		
		oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();        
		that.fnDraw();                 
		
		if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )        
		{            
			oSettings._iDisplayStart = iStart;            
			that.fnDraw( false );        
		}
		
		that.oApi._fnProcessingDisplay( oSettings, false );
		
		/* Callback user function - for event handlers etc */        
		if ( typeof fnCallback == 'function' && fnCallback != null )        
		{            
			fnCallback( oSettings );        
		}    
	}, oSettings );
}